package com.cuanbobox.tcp.wds;

import android.text.TextUtils;

import com.cuanbobox.utils.LogUtil;

import java.io.IOException;
import java.net.ConnectException;
import java.net.Socket;
import java.util.Date;

/**
 * 矩阵初始化线程
 */
public class WindowsInitThread extends Thread {
    private String ip;
    private int port;
    private Socket socket;
    //Socket是否已连接
    public boolean isConnected;
    private WindowsReceiveThread tcpReceiveThread;
    private WindowsSendThread tcpSendThread;

    public WindowsInitThread(String ip, int port) {
        this.ip = ip;
        this.port = port;
        isConnected = false;
    }

    @Override
    public void run() {
        super.run();
        if(TextUtils.isEmpty(ip))return;
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        startConnect();
    }

    public void close() {
        if (socket != null) {
            try {
                tcpSendThread.stopThread();
                tcpReceiveThread.stopThread();
                socket.close();
                socket = null;
                isConnected = false;
            } catch (Exception e) {

            }
        }
        LogUtil.add("状态","关闭TCP","互动TCP");
    }

    private void startConnect() {
        try {
            socket = new Socket(ip, Integer.valueOf(port));
            socket.setKeepAlive(true);
            //设置心跳包
            //socket.sendUrgentData(0xFF);
            LogUtil.add("状态","尝试连接","互动TCP");
            if (socket.isConnected()) {
                WindowsReceiveThread.recordTime=new Date().getTime();
                LogUtil.add("状态","连接成功","互动TCP");
                isConnected = true;
                tcpSendThread = new WindowsSendThread(this);
                tcpSendThread.start();
                tcpReceiveThread = new WindowsReceiveThread(this);
                tcpReceiveThread.start();
            }
        }catch (Exception e) {
            LogUtil.addError("---------------WindowsInitThread-----------------");
            LogUtil.addError(e);
            LogUtil.addError("---------------end-----------------");
            isConnected = false;
        }
    }

    public boolean isConnected() {
        return isConnected;
    }

    public void setConnected(boolean connected) {
        isConnected = connected;
    }

    public String getIp() {
        return ip;
    }

    public int getPort() {
        return port;
    }

    public Socket getSocket() {
        return socket;
    }
}
